package model

import (
	"gorm.io/gorm"
)

// 租户查询条件结构体
type TenantCondition struct {
	ID            string   `json:"id"`
	Name          string   `json:"name"`
	ServerStartAt string   `json:"server_start_at"`
	ServerEndAt   string   `json:"server_end_at"`
	IDs           []string `json:"ids"`
}

type TenantClient struct {
	db *gorm.DB
}

func NewTenantClient(db *gorm.DB) *TenantClient {
	return &TenantClient{db: db}
}

// 创建租户
func (tc *TenantClient) CreateTenant(tenant *Tenant) error {
	return tc.db.Create(tenant).Error
}

// 更新租户
func (tc *TenantClient) UpdateTenant(tenant *Tenant) error {
	data := map[string]interface{}{}

	if tenant.Name != "" {
		data["name"] = tenant.Name
	}
	if tenant.ServerStartAt != "" {
		data["server_start_at"] = tenant.ServerStartAt
	}
	if tenant.ServerEndAt != "" {
		data["server_end_at"] = tenant.ServerEndAt
	}

	return tc.db.Model(&Tenant{}).Where("id = ?", tenant.ID).Updates(data).Error
}

// 根据条件查询租户
func (tc *TenantClient) FindTenantByCondition(condition *TenantCondition) (*Tenant, error) {
	// 构建query
	query := tc.db.Model(&Tenant{})
	// 根据条件查找用户
	if condition.ID != "" {
		query = query.Where("id = ?", condition.ID)
	}
	if condition.Name != "" {
		query = query.Where("name LIKE ?", "%"+condition.Name+"%")
	}
	if condition.ServerStartAt != "" {
		query = query.Where("server_start_at > ?", condition.ServerStartAt)
	}
	if condition.ServerEndAt != "" {
		query = query.Where("server_end_at < ?", condition.ServerEndAt)
	}

	// 执行查询
	var tenant *Tenant
	err := query.First(&tenant).Error
	return tenant, err
}

func (tc *TenantClient) BatchFindTenantByCondition(condition *TenantCondition, page, size int) ([]*Tenant, error) {
	// 构建query
	query := tc.db.Model(&Tenant{})
	// 根据条件查找用户
	if condition.Name != "" {
		query = query.Where("name LIKE ?", "%"+condition.Name+"%")
	}
	if condition.ServerStartAt != "" {
		query = query.Where("server_start_at > ?", condition.ServerStartAt)
	}
	if condition.ServerEndAt != "" {
		query = query.Where("server_end_at < ?", condition.ServerEndAt)
	}
	if len(condition.IDs) > 0 {
		query = query.Where("id IN (?)", condition.IDs)
	}

	// 分页查询
	query = query.Offset((page - 1) * size).Limit(size).Order("created_at desc")

	// 执行查询
	var tenants []*Tenant
	err := query.Find(&tenants).Error
	return tenants, err
}

// 批量查询租户
func (tc *TenantClient) BatchFindTenant(ids []string) ([]*Tenant, error) {
	var tenants []*Tenant
	err := tc.db.Model(&Tenant{}).Where("id IN (?)", ids).Find(&tenants).Error
	return tenants, err
}
